<template>
  <div class="strategy-container">
    <!-- 策略选择器 -->
    <el-tabs v-model="activeStrategy" @tab-change="handleStrategyChange">
      <el-tab-pane label="双低策略" name="double-low">
        <div class="strategy-params">
          <el-card class="param-card" shadow="hover">
            <template #header>
              <div class="param-header">
                <span>策略参数配置</span>
                <el-button-group>
                  <el-button type="primary" @click="applyDefaultParams">默认参数</el-button>
                  <el-button type="success" @click="fetchDoubleLowData">应用策略</el-button>
                </el-button-group>
              </div>
            </template>
            
            <el-form :model="doubleLowParams" label-position="top">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="价格区间">
                    <div class="param-value-display">
                      <span>{{ doubleLowParams.priceRange[0] }} - {{ doubleLowParams.priceRange[1] }} 元</span>
                    </div>
                    <el-slider
                      v-model="doubleLowParams.priceRange"
                      range
                      :min="0"
                      :max="300"
                      :marks="{
                        90: '90',
                        110: '110',
                        130: '130',
                        150: '150'
                      }"
                      :format-tooltip="value => value + '元'"
                      class="custom-slider"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="最大溢价率">
                    <div class="param-value-display">
                      <span>{{ doubleLowParams.maxPremium }}%</span>
                    </div>
                    <el-slider
                      v-model="doubleLowParams.maxPremium"
                      :min="0"
                      :max="100"
                      :marks="{
                        20: '20%',
                        30: '30%',
                        50: '50%'
                      }"
                      :format-tooltip="value => value + '%'"
                      class="custom-slider"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="筛选数量">
                    <el-input-number
                      v-model="doubleLowParams.topN"
                      :min="1"
                      :max="100"
                      :step="5"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <div class="param-tips">
                    <el-alert
                      title="策略说明"
                      type="info"
                      description="双低策略根据转债价格和溢价率进行筛选，一般建议价格90-130元，溢价率低于30%"
                      :closable="false"
                      show-icon
                    />
                  </div>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </div>

        <!-- 双低策略结果展示 -->
        <div class="strategy-results" v-if="doubleLowData">
          <div class="data-info">
            <span>更新时间: {{ doubleLowData.update_time }}</span>
            <el-tag>{{ doubleLowData.strategy_name }}</el-tag>
          </div>
          
          <!-- 散点图 -->
          <div class="chart-container">
            <v-chart class="chart" :option="scatterOption" autoresize/>
          </div>

          <!-- 数据表格 -->
          <el-table 
            :data="doubleLowData?.data" 
            stripe 
            style="width: 100%"
            height="400"
            :default-sort="{prop: 'double_low', order: 'ascending'}"
          >
            <el-table-column
              v-for="col in tableColumns"
              :key="col.prop"
              :prop="col.prop"
              :label="col.label"
              :width="col.width"
              :sortable="col.sortable"
              :formatter="col.formatter"
            >
              <template #default="scope" v-if="col.prop === 'double_low'">
                <el-progress
                  :percentage="getDoubleLowPercentage(scope.row.double_low)"
                  :color="getDoubleLowColor(scope.row.double_low)"
                  :format="(percentage) => scope.row.double_low.toFixed(2)"
                  :stroke-width="15"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 策略组合追踪标签页 -->
      <el-tab-pane label="策略组合追踪" name="portfolio">
        <el-card class="portfolio-card">
          <template #header>
            <div class="param-header">
              <span>组合追踪设置</span>
              <el-radio-group v-model="portfolioParams.strategy">
                <el-radio-button value="double_low">双低策略</el-radio-button>
                <el-radio-button value="triple_low">三低策略</el-radio-button>
              </el-radio-group>
              <el-select v-model="portfolioParams.track_days" style="width: 120px">
                <el-option label="近30天" :value="30"/>
                <el-option label="近60天" :value="60"/>
                <el-option label="近90天" :value="90"/>
              </el-select>
              <el-button type="primary" @click="fetchPortfolioData">追踪分析</el-button>
            </div>
          </template>
          
          <!-- 策略收益率走势 -->
          <el-row :gutter="20" v-if="portfolioData">
            <el-col :span="16">
              <v-chart class="chart" :option="returnsTrendOption" autoresize/>
            </el-col>
            <el-col :span="8">
              <div class="portfolio-stats">
                <div class="stat-item">
                  <span class="label">最大回撤</span>
                  <span class="value" :class="getValueClass(portfolioData.max_drawdown)">
                    {{ portfolioData.max_drawdown }}%
                  </span>
                </div>
                <div class="stat-item">
                  <span class="label">年化收益</span>
                  <span class="value" :class="getValueClass(portfolioData.annualized_return)">
                    {{ portfolioData.annualized_return }}%
                  </span>
                </div>
                <v-chart class="pie-chart" :option="holdingsOption" autoresize/>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-tab-pane>

      <!-- 综合分析标签页 -->
      <el-tab-pane label="综合分析" name="comprehensive">
        <el-card class="comprehensive-card">
          <template #header>
            <div class="filter-header">
              <span>综合筛选条件</span>
              <el-button-group>
                <el-button @click="applyConservativeFilter">保守策略</el-button>
                <el-button @click="applyBalancedFilter">平衡策略</el-button>
                <el-button @click="applyAggressiveFilter">进取策略</el-button>
              </el-button-group>
            </div>
          </template>

          <el-form :model="comprehensiveParams" label-width="120px" class="filter-form">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="价格区间">
                  <el-slider
                    v-model="comprehensiveParams.priceRange"
                    range
                    :min="0"
                    :max="300"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最小规模(亿)">
                  <el-input-number v-model="comprehensiveParams.min_size" :min="0" :step="0.5"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最大负债率(%)">
                  <el-input-number v-model="comprehensiveParams.max_debt_ratio" :min="0" :max="100"/>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="最小现金流(亿)">
                  <el-input-number v-model="comprehensiveParams.min_cash_flow" :min="0" :step="0.5"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="返回数量">
                  <el-input-number v-model="comprehensiveParams.top_n" :min="1" :max="100"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-button type="primary" @click="fetchComprehensiveData">应用筛选</el-button>
              </el-col>
            </el-row>
          </el-form>

          <!-- 综合分析结果展示 -->
          <div v-if="comprehensiveData" class="analysis-results">
            <el-row :gutter="20">
              <el-col :span="6" v-for="(value, key) in comprehensiveData.analysis" :key="key">
                <el-card shadow="hover" class="analysis-card">
                  <statistic :title="getAnalysisTitle(key)" :value="value" :precision="2"/>
                </el-card>
              </el-col>
            </el-row>

            <!-- 散点矩阵图 -->
            <div class="matrix-chart">
              <v-chart :option="matrixOption" autoresize/>
            </div>

            <!-- 数据表格 -->
            <el-table
              :data="comprehensiveData.data"
              style="width: 100%"
              :default-sort="{prop: 'finance_score', order: 'descending'}"
            >
              <el-table-column type="expand">
                <template #default="props">
                  <el-row>
                    <el-col :span="12">
                      <v-chart class="radar-chart" :option="getRadarOption(props.row)" autoresize/>
                    </el-col>
                    <el-col :span="12">
                      <el-descriptions title="详细指标" :column="2" border>
                        <el-descriptions-item label="发行规模">{{ props.row.issue_size }}亿</el-descriptions-item>
                        <el-descriptions-item label="负债率">{{ props.row.debt_ratio }}%</el-descriptions-item>
                        <el-descriptions-item label="经营现金流">{{ props.row.operating_cashflow }}亿</el-descriptions-item>
                        <el-descriptions-item label="综合评分">{{ props.row.finance_score }}</el-descriptions-item>
                      </el-descriptions>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column prop="bond_code" label="代码" width="100"/>
              <el-table-column prop="bond_nm" label="名称" width="120"/>
              <el-table-column prop="price" label="价格" sortable/>
              <el-table-column prop="premium_rt" label="溢价率" sortable/>
              <el-table-column prop="finance_score" label="评分" sortable>
                <template #default="scope">
                  <el-tag :type="getScoreTagType(scope.row.finance_score)">
                    {{ scope.row.finance_score }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { use } from 'echarts/core';
import { ScatterChart, LineChart, PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  VisualMapComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import VChart from 'vue-echarts';
import http from '@/utils/http';
import { ElMessage } from 'element-plus';

// 注册必要的组件
use([
  CanvasRenderer,
  ScatterChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  VisualMapComponent,
  LineChart,
  PieChart
]);

// 状态管理
const activeStrategy = ref('double-low');
const doubleLowData = ref(null);
const doubleLowParams = ref({
  priceRange: [90, 130],
  maxPremium: 30,
  topN: 30
});

const portfolioParams = ref({
  strategy: 'double_low',
  track_days: 30
});

const comprehensiveParams = ref({
  priceRange: [90, 130],
  min_size: 5.0,
  max_debt_ratio: 60.0,
  min_cash_flow: 1.0,
  top_n: 30
});

const portfolioData = ref(null);
const comprehensiveData = ref(null);

// 散点图配置
const scatterOption = computed(() => ({
  title: {
    text: '双低策略分析散点图',
    subtext: doubleLowData.value?.description || ''
  },
  tooltip: {
    trigger: 'item',
    formatter: params => {
      const [price, premium, doubleLow, bondNm, bondCode] = params.data;
      return `
        ${bondNm}（${bondCode}）<br/>
        价格: ${price.toFixed(2)}元<br/>
        溢价率: ${premium.toFixed(2)}%<br/>
        双低值: ${doubleLow.toFixed(2)}
      `;
    }
  },
  xAxis: {
    type: 'value',
    name: '转债价格',
    min: 90,
    max: 140,
    splitLine: { show: true }
  },
  yAxis: {
    type: 'value',
    name: '溢价率(%)',
    min: -80,
    max: 40,
    splitLine: { show: true }
  },
  visualMap: {
    min: 0,
    max: 150,
    dimension: 2,
    orient: 'horizontal',
    top: 10,
    right: 10,
    text: ['双低值高', '双低值低'],
    inRange: {
      color: ['#52c41a', '#faad14', '#f5222d'],
      symbolSize: [10, 25]
    }
  },
  series: [{
    type: 'scatter',
    data: doubleLowData.value?.data.map(item => [
      item.price,
      item.premium_rt,
      item.double_low,
      item.bond_nm,
      item.bond_code
    ]) || [],
    animationDelay: (idx) => idx * 5
  }]
}));

// 修改数据表格列配置
const tableColumns = [
  {
    prop: 'bond_code',
    label: '转债代码',
    width: 100
  },
  {
    prop: 'bond_nm',
    label: '转债名称',
    width: 120
  },
  {
    prop: 'price',
    label: '价格',
    width: 100,
    sortable: true,
    formatter: (row) => row.price.toFixed(2)
  },
  {
    prop: 'premium_rt',
    label: '溢价率',
    width: 100,
    sortable: true,
    formatter: (row) => row.premium_rt.toFixed(2) + '%'
  },
  {
    prop: 'double_low',
    label: '双低值',
    width: 120,
    sortable: true,
    formatter: (row) => row.double_low.toFixed(2)
  }
];

// 获取双低策略数据
const fetchDoubleLowData = async () => {
  try {
    const response = await http.get('/strategies/double-low', {
      params: {
        min_price: doubleLowParams.value.priceRange[0],
        max_price: doubleLowParams.value.priceRange[1],
        max_premium: doubleLowParams.value.maxPremium,
        top_n: doubleLowParams.value.topN
      }
    });
    

      doubleLowData.value = response;
      ElMessage.success('双低策略数据获取成功');

  } catch (error) {
    console.error('获取双低策略数据失败:', error);
    ElMessage.error('获取策略数据失败');
  }
};

// 策略组合追踪相关方法
const fetchPortfolioData = async () => {
  try {
    const response = await http.get('/strategies/portfolio-tracking', {
      params: portfolioParams.value
    });
    portfolioData.value = response;
  } catch (error) {
    console.error('获取组合追踪数据失败:', error);
    ElMessage.error('获取组合追踪数据失败');
  }
};

// 综合分析相关方法
const fetchComprehensiveData = async () => {
  try {
    const response = await http.get('/strategies/comprehensive-analysis', {
      params: {
        min_price: comprehensiveParams.value.priceRange[0],
        max_price: comprehensiveParams.value.priceRange[1],
        min_size: comprehensiveParams.value.min_size,
        max_debt_ratio: comprehensiveParams.value.max_debt_ratio,
        min_cash_flow: comprehensiveParams.value.min_cash_flow,
        top_n: comprehensiveParams.value.top_n
      }
    });
    comprehensiveData.value = response;
  } catch (error) {
    console.error('获取综合分析数据失败:', error);
    ElMessage.error('获取综合分析数据失败');
  }
};

// 图表配置
const returnsTrendOption = computed(() => ({
  // ... 收益率走势图配置
}));

const holdingsOption = computed(() => ({
  // ... 持仓结构饼图配置
}));

const matrixOption = computed(() => ({
  // ... 散点矩阵图配置
}));

// 工具函数
const getValueClass = (value) => {
  if (value > 0) return 'positive';
  if (value < 0) return 'negative';
  return 'neutral';
};

const getScoreTagType = (score) => {
  if (score >= 8) return 'success';
  if (score >= 6) return 'warning';
  return 'danger';
};

// 策略预设
const applyConservativeFilter = () => {
  comprehensiveParams.value = {
    priceRange: [90, 110],
    min_size: 10.0,
    max_debt_ratio: 40.0,
    min_cash_flow: 2.0,
    top_n: 30
  };
};

// 添加策略切换处理函数
const handleStrategyChange = async (strategy) => {
  try {
    switch(strategy) {
      case 'double-low':
        await fetchDoubleLowData();
        break;
      case 'portfolio':
        await fetchPortfolioData();
        break;
      case 'comprehensive':
        await fetchComprehensiveData();
        break;
    }
  } catch (error) {
    console.error('切换策略失败:', error);
    ElMessage.error('切换策略失败');
  }
};

// 样式工具函数
const getPriceClass = (price) => {
  if (price < 100) return 'text-success';
  if (price < 110) return 'text-warning';
  return 'text-danger';
};

const getPremiumClass = (premium) => {
  if (premium < 20) return 'text-success';
  if (premium < 40) return 'text-warning';
  return 'text-danger';
};

const getDoubleLowPercentage = (value) => {
  return Math.min(100, (value / 150) * 100); // 假设150是最大双低值
};

const getDoubleLowColor = (value) => {
  if (value < 100) return '#67C23A';
  if (value < 130) return '#E6A23C';
  return '#F56C6C';
};

// 添加默认参数设置函数
const applyDefaultParams = () => {
  doubleLowParams.value = {
    priceRange: [90, 130],
    maxPremium: 30,
    topN: 30
  };
};
</script>

<style scoped>
.strategy-container {
  padding: 20px;
}

.strategy-params {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.strategy-results {
  margin-top: 20px;
}

.data-info {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 400px;
  margin-bottom: 20px;
}

.chart {
  height: 100%;
}

.text-success { color: #67C23A; }
.text-warning { color: #E6A23C; }
.text-danger { color: #F56C6C; }

.param-card {
  margin-bottom: 20px;
}

.param-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.param-value-display {
  text-align: center;
  margin-bottom: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.custom-slider {
  margin: 10px 0 25px;
}

.custom-slider :deep(.el-slider__marks-text) {
  color: #606266;
  font-size: 12px;
}

.param-tips {
  margin-top: 22px;  /* 对齐输入框 */
}

.el-form-item {
  margin-bottom: 0;
}

.portfolio-card,
.comprehensive-card {
  margin-bottom: 20px;
}

.portfolio-stats {
  padding: 20px;
}

.stat-item {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.radar-chart,
.pie-chart {
  height: 300px;
}

.matrix-chart {
  height: 500px;
  margin: 20px 0;
}

.positive { color: #67C23A; }
.negative { color: #F56C6C; }
.neutral { color: #909399; }

.analysis-card {
  margin-bottom: 20px;
}

.filter-form {
  padding: 20px 0;
}
</style>
